package com.imageim.yimirror.ui.widght;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.util.UserUtil;
import com.makeramen.roundedimageview.RoundedImageView;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 扫码领红包
 * Created by Bruce.Zhou on 2019/1/22 10:10.
 * Email: 907160968@qq.com
 */
public class QrcodeRedPkgView extends RelativeLayout {
    Unbinder unbinder;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.iv_qrcode)
    RoundedImageView ivQrcode;
    @BindView(R.id.tv_jump_timer)
    TextView tvJumpTimer;
    @BindView(R.id.iv_firework_small)
    ImageView ivFireworkSmall;
    @BindView(R.id.iv_firework_big)
    ImageView ivFireworkBig;

    private static final int MSG_SCAN_STATUS = 0X01;
    private CountDownTimer timer;

    static class MyHandler extends Handler {

        private WeakReference<QrcodeRedPkgView> reference;

        public MyHandler(QrcodeRedPkgView view) {
            reference = new WeakReference<>(view);
        }

        @Override
        public void handleMessage(Message msg) {
            QrcodeRedPkgView view = reference.get();
            if (view != null) {
                switch (msg.what) {
                    case MSG_SCAN_STATUS: // 轮询扫码状态
                        removeMessages(MSG_SCAN_STATUS);
                        view.getScanQrcodeStatus();
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private MyHandler handler;

    public interface OnJumpListener {
        void onJump(); // 点击跳过按钮

        void onTimerOver(); // 倒计时结束

        void finishScanQrcode(); // 扫码成功
    }

    private OnJumpListener onJumpListener;

    public void setOnJumpListener(OnJumpListener onJumpListener) {
        this.onJumpListener = onJumpListener;
    }

    public QrcodeRedPkgView(Context context) {
        super(context);
        init();
    }

    public QrcodeRedPkgView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public QrcodeRedPkgView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public QrcodeRedPkgView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        View view = View.inflate(getContext(), R.layout.layout_scan_red_pkg, this);
        ButterKnife.bind(view);

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvJumpTimer.setText("跳过（" + millisUntilFinished / 1000 + "s）");
            }

            @Override
            public void onFinish() {
                if (onJumpListener != null) {
                    onJumpListener.onTimerOver();
                    handler.removeCallbacksAndMessages(null);
                }
            }
        };

        ivFireworkBig.setVisibility(View.INVISIBLE);
        ivFireworkSmall.setVisibility(View.INVISIBLE);

        handler = new MyHandler(this);
        //        // 获取二维码和红包金额
        //        getMoneyQrcode();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (unbinder != null) {
            unbinder.unbind();
        }

        if (timer != null) {
            timer.cancel();
        }
        handler.removeCallbacksAndMessages(null);
    }


    @OnClick(R.id.btn_jump_over)
    public void onViewClicked() {
        if (onJumpListener != null) {
            onJumpListener.onJump();
            handler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 以动画效果显示
     */
    public void show() {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(this, "scaleX", 0, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(this, "scaleY", 0, 1);
        AnimatorSet anim = new AnimatorSet();
        scaleX.setInterpolator(new OvershootInterpolator(1.2f));
        scaleY.setInterpolator(new OvershootInterpolator(1.2f));
        anim.setDuration(1400);
        anim.playTogether(scaleX, scaleY);
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                startFireWorkAnim(ivFireworkBig, 400);
                startFireWorkAnim(ivFireworkSmall, 700);
                timer.start();
                // 轮询二维码扫码状态
                handler.sendEmptyMessageDelayed(MSG_SCAN_STATUS, 1000);
            }
        });
        anim.start();
        setVisibility(View.VISIBLE);
    }

    public void hide() {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1, 0);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1, 0);
        AnimatorSet anim = new AnimatorSet();
        scaleX.setInterpolator(new AccelerateInterpolator());
        scaleY.setInterpolator(new AccelerateInterpolator());
        anim.setDuration(1500);
        anim.playTogether(scaleX, scaleY);
        anim.start();

        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (timer != null) {
                    timer.cancel();
                }
            }
        });


    }

    /**
     * 烟花
     *
     * @param fireworkView
     * @param delay
     */
    private void startFireWorkAnim(View fireworkView, long delay) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(fireworkView, "scaleX", 0, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(fireworkView, "scaleY", 0, 1);
        scaleX.setInterpolator(new DecelerateInterpolator());
        scaleY.setInterpolator(new DecelerateInterpolator());
        ObjectAnimator scaleDownX = ObjectAnimator.ofFloat(fireworkView, "scaleX", 1, 0.8f);
        ObjectAnimator scaleDownY = ObjectAnimator.ofFloat(fireworkView, "scaleY", 1, 0.8f);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(fireworkView, "alpha", 1, 0);

        AnimatorSet scaleUp = new AnimatorSet();
        scaleUp.playTogether(scaleX, scaleY);
        scaleUp.setDuration(1800);

        AnimatorSet scaleDown = new AnimatorSet();
        scaleDown.playTogether(scaleDownX, scaleDownY, alpha);
        scaleDown.setDuration(2000);

        AnimatorSet anim = new AnimatorSet();
        anim.playSequentially(scaleUp, scaleDown);
        anim.setStartDelay(delay);
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                fireworkView.setVisibility(View.VISIBLE);
                fireworkView.setAlpha(1);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                fireworkView.setVisibility(View.INVISIBLE);
            }
        });
        anim.start();
    }

    /**
     * 设置红包金额
     *
     * @param money
     */
    @SuppressLint("DefaultLocale")
    public void setMoney(float money) {
        tvMoney.setText(String.format("%.2f", money));
    }

    /**
     * 设置二维码链接
     *
     * @param qrcodeUrl
     */
    public void setQrcode(String qrcodeUrl) {
        Bitmap bitmap = BitmapUtils.getQrcodeBitmapWithPadding(qrcodeUrl, 270, Color.BLACK, 15);
        ivQrcode.setImageBitmap(bitmap);
    }

    //    /**
    //     * net获取金额和二维码
    //     */
    //    private void getMoneyQrcode() {
    //        String params = "";
    //        NetUtil.getObject(getContext(), NetConstants.URL.GET_REDPKG_QRCODE, params, new NetCallback<String>() {
    //            @Override
    //            public void onStart() {
    //            }
    //
    //            @Override
    //            public void onSuccess(String result) {
    //                try {
    //                    JSONObject resultObj = new JSONObject(result);
    //                    float money = Float.valueOf(resultObj.getString("money"));
    //                    String qrCodeUrl = resultObj.getString("qrcodeUrl");
    //                    // 设置二维码
    //                    setQrcode(qrCodeUrl);
    //                    // 设置金额
    //                    setMoney(money);
    //                    // 轮询二维码扫码状态
    //                    handler.sendEmptyMessageDelayed(MSG_SCAN_STATUS, 1500);
    //                } catch (JSONException e) {
    //                    e.printStackTrace();
    //                }
    //            }
    //
    //            @Override
    //            public void onFail(int errorCode, String errorMsg) {
    //                TipUtil.show(errorMsg + errorCode);
    //            }
    //        });
    //    }

    /**
     * 获取扫码状态
     */
    private void getScanQrcodeStatus() {
        String params = "photoNo=" + UserUtil.getPhotoNo();
        NetUtil.getObject(getContext(), NetConstants.URL.SCAN_REDPKG_STATUS, params, new NetCallback<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String result) {
                // 根据扫码状态判断下一步，扫完则关闭扫码界面，并显示扫码成功
                try {
                    JSONObject resultObj = new JSONObject(result);
                    int hasScan = resultObj.optInt("scanRedQrcodeFlag", 2);
                    if (hasScan == 1) {
                        if (onJumpListener != null) {
                            onJumpListener.finishScanQrcode();
                        }
                    } else { // 未扫码继续轮询
                        handler.sendEmptyMessageDelayed(MSG_SCAN_STATUS, 800);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
            }
        });
    }
}
